// pages/waiFor-comment/waiFor-comment.js
import {
	userComment,
	userOrder,
	fileupload
} from '../../utils/request/apiurl'
import api from '../../utils/request/api'

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		goodList: [],
		tasteList: [{
				id: 1,
				name: '好评',
				current: false,
				value: 3
			},
			{
				id: 2,
				name: '中评',
				current: false,
				value: 2
			},
			{
				id: 3,
				name: '差评',
				current: false,
				value: 1
			}
		],
		tasteNav: 0, //评价
		goodId: "",
		rank:'',
		imgList: [],
		uid: ''
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		console.log(options)
		var userInfo = wx.getStorageSync('userInfo')
		this.setData({
			uid: userInfo.uid,
			rank:userInfo.rank
		})
		let id = options.id
		//获取商品详情
		api.post(userOrder.orderById, {
			id: id
		}).then(res => {
			// console.log(res)
			this.setData({
				goodList: res,
				goodId: res.gid,
				orderId: res.oid
			})
		}).catch(err => {
			wx.showToast({
				title: err.message,
				icon: 'none'
			})
		})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {
		// wx.showNavigationBarLoading() //在标题栏中显示加载
		// this.onLoad()
		// setTimeout(function() {
		// 	wx.hideNavigationBarLoading() //完成停止加载
		// 	wx.stopPullDownRefresh() //停止下拉刷新
		// }, 1500);
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
	// 选择分类
	changeTasteTab(event) {
		const currentIndex = event.currentTarget.dataset.index;
		const currentId = event.currentTarget.dataset.id;
		// 给当前项增加class
		if (this.data.tasteNav !== currentIndex) {
			this.setData({
				tasteNav: currentIndex
			})
		}
	},
	// 上传图片
	changeImage() {
		var _this = this;
		console.log(this.data.imgList.length,"==============>")
		if (this.data.imgList.length < 5) {
			// wx.chooseImage({
			//   count: 5,
			//   sizeType: ['original', 'compressed'],
			//   sourceType: ['album', 'camera'],
			//   success(res) {
			//     // console.log(res)
			//     _this.setData({
			//       imgList: [..._this.data.imgList, ...res.tempFilePaths]
			//     })
			//   }
			// })
			wx.chooseImage({
        count: 5 - this.data.imgList.length,
				success(res) {
					// console.log(res)
					var tempFilePaths = res.tempFilePaths
					wx.showToast({
						title: '正在上传...',
						icon: 'loading',
						mask: true,
						duration: 2000
					})
					var uploadImgCount = 0;

					for (var i = 0, h = tempFilePaths.length; i < h; i++) {
						wx.uploadFile({
							url: 'https://backstage.dfbs-vm.com/boda/goods/uploadCommentPicture',
							filePath: tempFilePaths[i],
							name: 'file',
							formData: {
								'imgIndex': i,
								userId: _this.data.uid,
							},
							header: {
								"Content-Type": "multipart/form-data"
							},
							success: function(res) {
								// console.log(res)
								uploadImgCount++;
								var data = JSON.parse(res.data).data;
								//服务器返回格式: { "Catalog": "testFolder", "FileName": "1.jpg", "Url": "https://test.com/1.jpg" }  
								var imgList = _this.data.imgList;
								if (imgList == null) {
									imgList = [];
								}
								// _this.data.imgList.push({
								// 	// "catalog": _this.Catalog,
								// 	// "fileName": _this.FileName,
								// 	// "url": _this.Url
								// });
								_this.data.imgList.push(data)
								_this.setData({
									imgList: _this.data.imgList
								});
								// console.log( _this.data.imgList,' _this.data.imgList')
								//如果是最后一张,则隐藏等待中  
								if (uploadImgCount == tempFilePaths.length) {
									wx.hideToast();
								}
							},
							fail: function(res) {
								wx.hideToast();
								wx.showModal({
									title: '错误提示',
									content: '上传图片失败',
									showCancel: false,
									success: function(res) {}
								})
							}
						});
					}




					//  wx.uploadFile({
					// // url: fileupload.path,
					// url:'https://backstage.dfbs-vm.com/boda/goods/uploadCommentPicture',
					// filePath:tempFilePaths.toString(),
					// name: 'file',
					// formData: {
					//   // ClientIdentityMT: "PC",
					//   userId: _this.data.uid,
					// },
					// success(res) {
					// 	console.log(res)
					//   let data = JSON.parse(res.data).data
					//   _this.data.imgList.push(data) 
					//   _this.setData({
					// 	imgList: _this.data.imgList
					//   })
					// }
					// })  
				}
			})
		} else {
			wx.showToast({
				title: '最多只能选择5张图片',
				icon: 'none',
				duration: 1000
			})
		}
	},
	formBox: function(e) {
		//提交评论
		let info = e.detail.value.comment
		if (info) {
			api.post(userComment.comment, {
				uid: wx.getStorageSync('userInfo').uid,
				info: info,
				goodsId: this.data.goodId,
				url: this.data.imgList.join(","),
				status: this.data.tasteList[this.data.tasteNav].value,
				orderId: this.data.orderId
			}).then(res => {
				console.log(res)
				wx.redirectTo({
					url: '../myOrder/myOrder?type=5'
				})
			}).catch(err => {
				wx.showToast({
					title: err.message,
					icon: 'none'
				})
			})
		} else {
			wx.showToast({
				title: '请填写评价',
				icon: 'none',
				duration: 1000
			})
		}
	},
	//删除图片
	deleteImg(e) {
		let index = e.target.dataset['index']
		let that = this
		wx.showModal({
			title: '删除图片',
			content: '是否确认删除这张图片？',
			success: function(res) {
				if (res.confirm) {
					let imgList = that.arrDeleteByIndex(that.data.imgList, index)
					that.setData({
						imgList: imgList
					})
					// console.log(imgList)
				}
			}
		})
	},
	//数组删除成员
	arrDeleteByIndex(arr, index) {
		if (!Array.isArray(arr)) return []
		if (!arr.length) return []
		const data = []
		for (let i = 0; i < arr.length; i++) {
			if (i != index) {
				data.push(arr[i])
			}
		}
		return data
	}
})
